/**
 * 
 */
package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import util.LivrariaUtils;

/**
 * @author Eve
 * 
 */
public class VendaDAO {

	private ItemVendaDAO itemVendaDAO = new ItemVendaDAO();

	public boolean registrarVenda(Venda venda) {
		boolean retorno = false;
		try {
			Connection conexao = ConexaoBD.getInstance().conectar();
			String cmdSQL = "INSERT INTO VENDA_01083333 (DATAVENDA,TOTALVENDA,TOTALITENSVENDA)"
					+ " VALUES ('"
					+ LivrariaUtils.convertToTimestamp(venda.getDataVenda())
					+ "',"
					+ venda.getTotalVenda()
					+ ", "
					+ venda.getQtdeItens() + ")";
			Statement st = conexao.createStatement();
			st.executeUpdate(cmdSQL, PreparedStatement.RETURN_GENERATED_KEYS);
			ResultSet rs = st.getGeneratedKeys();
			rs.next();
			venda.setIdVenda(rs.getInt(1));
			retorno = true;
			if (retorno) {
				retorno = itemVendaDAO.registrarItensVenda(venda);
			}

			venda.notificar();

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return retorno;
	}

	public List<Venda> listarVendasDia() throws Exception {
		List<Venda> lstVendas = new ArrayList<Venda>();
		try {
			Connection conn = ConexaoBD.getInstance().conectar();
			PreparedStatement ps = conn
					.prepareStatement("SELECT totalVenda, totalItensVenda FROM VENDA_01083333 where DATAVENDA = CURRENT_DATE");
			ResultSet rs = ps.executeQuery();

			Venda venda = null;
			while (rs.next()) {
				venda = new Venda();
				venda.setTotalVenda(rs.getDouble("totalVenda"));
				venda.setQtdeItens(rs.getInt("totalItensVenda"));
				lstVendas.add(venda);
			}

		} catch (Throwable t) {
			t.printStackTrace();
		} finally {
			ConexaoBD.getInstance().desconectar();
		}
		return lstVendas;
	}

}
